import { actionTypeCreatorWithNameSpace, createAction } from './util';
import agent from 'agent';

const actionTypeCreator = actionTypeCreatorWithNameSpace('devTeam');

export const listByCurrentUser = createAction(actionTypeCreator('listByCurrentUser'), () => {
  return agent.get('api/users/current/dev-teams')
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});

export const getDetail = createAction(actionTypeCreator('getDetail'), (id) => {
  return agent.get(`/api/dev-teams/${id}/detail`)
    .then(response => response.body);
});

export const search = createAction(actionTypeCreator('search'), (query) => {
  return agent.get('/api/dev-teams')
    .query(query)
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});

export const setLeader = createAction(actionTypeCreator('setLeader'), (devTeamId, userId, enable) => {
  return agent.post(`/api/dev-teams/${devTeamId}/members/${userId}/leader`)
    .type('form')
    .send({enable})
    .then(() => {
      return {userId, enable};
    });
});

export const addMembers = createAction(actionTypeCreator('addMembers'), (devTeamId, userIds) => {
  return agent.post(`/api/dev-teams/${devTeamId}/members`)
    .type('form')
    .send({userIds})
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});

export const create = createAction(actionTypeCreator('create'), (devTeam) => {
  return agent.post('/api/dev-teams')
    .send(devTeam)
    .then(response => response.body);
});

export const removeMember = createAction(actionTypeCreator('removeMember'), (devTeamId, userId) => {
  return agent.del(`/api/dev-teams/${devTeamId}/members/${userId}`)
    .then(() => userId);
}, (devTeamId, userId) => {
  return {
    fetch: {
      processing: true,
      processingKey: userId
    }
  };
});

export const update = createAction(actionTypeCreator('update'), (devTeam) => {
  return agent.put(`/api/dev-teams/${devTeam.id}`)
    .send(devTeam)
    .then(() => devTeam);
}, {
  fetch: {
    processing: true
  }
});

export const suggest = createAction(actionTypeCreator('suggest'), (key) => {
  return agent.get('/api/dev-teams/suggest')
    .query({key})
    .then(response => response.body);
});

export const managedDevTeam = createAction(actionTypeCreator('managedDevTeam'), (companyId) => {
  const query = { companyId };
  return agent.get('/api/users/current/dev-team/managed')
    .query(query)
    .then(response => response.body);
}, {
  fetch: {
    processing: true
  }
});
